<script setup lang="ts">
import { ElMessage, FormInstance, UploadInstance } from 'element-plus';
import { ref, reactive, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { regionData } from 'element-china-area-data';
import ROUTER_CONSTANTS from '../route/constants';
import { registerUser } from '../services/user';
import Company from '../types/Company';
import useStore from '../store/modules/index.ts';


// 全局路由
const router = useRouter();
// UserStore
const userStore = useStore();
// 表单组件引用
const ruleFormRef = ref<FormInstance>();
// 公司头像上传组件引用
const uploadRef = ref<UploadInstance>();

// 注册页面表单响应式变量
const form = reactive<Company>({
  name: '',
  description: '',
  labels: [],
  process: '',
  size: '',
  location: [],
  url: '',
  production: '',
  intro: '',
  admin_username: '',
  admin_name: '',
  admin_password: '',
  admin_position: '',
});

// 表单规则
const rules = {
  name: [{ required: true, message: '请输入公司名称', trigger: 'blur' }],
  description: [{ required: true, message: '请输入公司标语', trigger: 'blur' }],
  labels: [{ required: true, message: '请选择标签', trigger: 'change' }],
  process: [{ required: true, message: '请选择融资进度', trigger: 'change' }],
  size: [{ required: true, message: '请输入公司人数', trigger: 'blur' }],
  location: [{ required: true, message: '请选择公司地址', trigger: 'blur' }],
  url: [{ required: true, message: '请输入公司网址', trigger: 'blur' }],
  production: [
    { required: true, message: '请输入公司产品介绍', trigger: 'blur' },
  ],
  intro: [{ required: true, message: '请输入公司介绍', trigger: 'blur' }],
  avatar: [{ required: true, message: '请上传公司头像', trigger: 'blur' }],
  admin_username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
  ],
  admin_name: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
  admin_password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
  admin_position: [{ required: true, message: '请输入职位', trigger: 'blur' }],
};

// 提交表单
const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  // 验证表单
  await formEl.validate(async (valid, fields) => {
    if (valid) {
      // 首先发送用户名和密码给后台，进行authenticate操作
      const registerResponse = await registerUser({ ...form });
      // 上传头像
      uploadRef.value?.submit();
      if (registerResponse.status === 200) {
        ElMessage.success('注册成功');
        const userInfo = registerResponse.data;
        // 保存用户信息
        userStore.setUser(userInfo);
        // 默认跳转到首页，即值为列表页
        router.replace({
          name: ROUTER_CONSTANTS.JOBLIST,
        });
      } else {
        // 将接口返回的错误信息赋值给errorMessage响应式变量
        ElMessage.error('登录发生错误');
      }
    } else {
      ElMessage.error('请仔细检查表单');
    }
  });
};

// 第一次进入页面，如果用户已经登录，则直接跳转到首页。
onMounted(() => {
  if (userStore.isLogin()) {
    router.replace({
      name: ROUTER_CONSTANTS.JOBLIST,
    });
  }
});

// 公司标签多选框列表内容
const companyLabelList = [
  '游戏',
  '社交平台',
  '区块链',
  '金融业',
  '影视',
  '电商平台',
  '短视频',
  '直播平台',
];

// 公司进度列表内容
const CompanyProcessList = [
  '天使轮',
  'A轮',
  'B轮',
  'C轮',
  'D轮',
  '上市公司',
  '未上市',
];

// 城市地址列表
const locationArea = regionData;
</script>

<template>
  <div class="register-layout">
    <el-container class="register-container" style="height: 100%">
      <el-header
        ><div class="register-title">PeekpaJob 管理系统注册表格</div></el-header
      >
      <el-main>
        <el-form
          ref="ruleFormRef"
          class="register-form"
          :model="form"
          :rules="rules"
          size="large"
        >
          <el-form-item label="公司名称" prop="name">
            <el-input v-model="form.name" placeholder="请输入" />
          </el-form-item>

          <el-form-item label="公司标语" prop="description">
            <el-input v-model="form.description" placeholder="请输入" />
          </el-form-item>
          <el-form-item label="公司标签" prop="labels">
            <el-select
              v-model="form.labels"
              multiple
              :multiple-limit="3"
              placeholder="请选择(多选，最多三个)"
              style="width: 100%"
            >
              <el-option
                v-for="item in companyLabelList"
                :key="item"
                :label="item"
                :value="item"
              />
            </el-select>
          </el-form-item>

          <el-form-item label="公司融资" prop="process">
            <el-select
              v-model="form.process"
              placeholder="请选择"
              style="width: 100%"
            >
              <el-option
                v-for="item in CompanyProcessList"
                :key="item"
                :label="item"
                :value="item"
              />
            </el-select>
          </el-form-item>

          <el-form-item label="公司规模" prop="size">
            <el-input v-model="form.size" type="number" placeholder="请输入">
              <template #append>人</template>
            </el-input>
          </el-form-item>

          <el-form-item label="公司地址" prop="location">
            <el-cascader
              v-model="form.location"
              :teleported="false"
              popper-class="select-popper"
              placeholder="请选择"
              :options="locationArea"
              style="width: 100%"
            ></el-cascader>
          </el-form-item>

          <el-form-item label="公司官网" prop="url">
            <el-input v-model="form.url" placeholder="请输入">
              <template #prepend>Http://</template>
            </el-input>
          </el-form-item>

          <el-form-item label="产品介绍" prop="production">
            <el-input
              v-model="form.production"
              type="textarea"
              placeholder="请输入"
            />
          </el-form-item>

          <el-form-item label="公司介绍" prop="intro">
            <el-input
              v-model="form.intro"
              type="textarea"
              placeholder="请输入"
            />
          </el-form-item>

          <el-form-item label="公司图标" prop="avatar">
            <el-upload
              ref="uploadRef"
              action="/api/image/post/"
              class="upload-demo"
              drag
              :auto-upload="false"
              multiple
            >
              <el-icon class="el-icon--upload"><eli-upload-filled /></el-icon>
              <div class="el-upload__text">
                请将图片拖拽或者 <em>点击选择</em>
              </div>
            </el-upload>
          </el-form-item>

          <el-form-item label="联系人邮箱" prop="admin_username">
            <el-input v-model="form.admin_username" placeholder="请输入" />
          </el-form-item>

          <el-form-item label="联系人姓名" prop="admin_name">
            <el-input v-model="form.admin_name" placeholder="请输入" />
          </el-form-item>

          <el-form-item label="联系人登录密码" prop="admin_password">
            <el-input
              v-model="form.admin_password"
              type="password"
              placeholder="请输入"
            />
          </el-form-item>

          <el-form-item label="联系人职位" prop="admin_position">
            <el-input v-model="form.admin_position" placeholder="请输入" />
          </el-form-item>

          <div class="register-btn">
            <el-button type="primary" @click="submitForm(ruleFormRef)"
              >注册</el-button
            >
          </div>
        </el-form>
      </el-main>
    </el-container>
  </div>
</template>

<style scoped>
.register-title {
  width: 100%;
  line-height: 50px;
  text-align: center;
  font-size: 30px;
  font-family: HyliaSerif;
}

.register-layout {
  height: 100%;
  background-color: #20b996;
}
.register-container {
  margin: auto;
}

.register-form {
  width: 600px;
  padding: 30px;
  border-radius: 5px;
  margin: 0 auto;
  background-color: #fff;
}

.register-btn button {
  width: 100%;
  text-align: center;
  background-color: #20b996;
}
</style>
